
package character_11_;

import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author Administrator
 */
public class Resource {
    
    private ReentrantLock lock = new ReentrantLock();
    private String name;

    public Resource(String name) {
        this.name = name;
    }
    
    void cooperate(Resource resource){
    
        while (true) {            
            try {
                if (lockMeAnd(resource)) {
                    System.out.println(this.name + "整合" + resource.name + "的资源");
                    break;
                }
            } finally {
                unLockMeAnd(resource);
            }
        }
        
    }

    private boolean lockMeAnd(Resource resource) {
         return this.lock.tryLock() && resource.lock.tryLock();
    }
    
    private void unLockMeAnd(Resource resource) {
        if (this.lock.isHeldByCurrentThread()) {
            this.lock.unlock();
        }
        if (resource.lock.isHeldByCurrentThread()) {
            resource.lock.unlock();
        }
    }
}
